import ColorThief from "colorthief";

class ColorExtractor {

  static isNearWhite = (color: number[]): boolean => {
    const threshold = 180;  // 设置阈值 ，越趋近255 越白
    return color[0] > threshold && color[1] > threshold && color[2] > threshold;
  };

  static getDominantColor(imageUrl: string): Promise<string> {
    return new Promise((resolve, reject) => {
      const colorThief = new ColorThief();
      const img = new Image();

      img.crossOrigin = "Anonymous"; // 允许跨域请求

      img.onload = () => {
        const dominantColor = colorThief.getColor(img);

        // 检查颜色是否接近白色
        if (!this.isNearWhite(dominantColor)) {
          resolve(dominantColor);
        } else {
          // 如果接近白色，尝试获取调色板并返回非接近白色的颜色
          const palette = colorThief.getPalette(img, 4); // 获取调色板
          const nonWhiteColor = palette.find(color => !this.isNearWhite(color)) || dominantColor;
          resolve(nonWhiteColor);
        }
      };

      img.onerror = (error) => {
        reject(`Error loading image: ${JSON.stringify(error)}`);
      };
      img.src = imageUrl;
    });
  }

  static getDominantColors(imageUrl: string, count: number = 3): Promise<number[][]> {
    return new Promise((resolve, reject) => {
      const colorThief = new ColorThief();
      const img = new Image();
      img.crossOrigin = "Anonymous"; // 允许跨域请求

      img.onload = () => {
        const palette = colorThief.getPalette(img, count); // 提取调色板
        resolve(palette);
      };

      img.onerror = (error) => {
        reject(`Error loading image: ${JSON.stringify(error)}`);
      };

      img.src = imageUrl;
    });
  }
}

export default ColorExtractor;
